//定义用户相关的仓库
import {defineStore} from "pinia";
import {reqCode, reqUserLogin} from "@/api/hospital";
import type {LoginData, UserLoginResponseData} from "@/api/hospital/type.ts";
import type {UserState} from "@/store/modules/interface";
import {GET_TOKEN, REMOVE_TOKEN, SET_TOKEN} from "@/utils/user.ts";
const useUserStore = defineStore('User',{
    state:():UserState=>{
        return{
            visible:false,//用于控制登录组件的dialog显示与隐藏
            code:'',//存储用户验证码
            // userInfo:({} as UserInfo)
            userInfo:JSON.parse(GET_TOKEN() as string)||{}
        }
    },
    actions:{
       async getCode(phone:string) {
           let result:any = await reqCode(phone);
           if(result.code==200){
               this.code=result.data;
               return 'ok';
           }else{
               return Promise.reject(new Error(result.message));
           }
       },
        //用户手机号码登录方法
        async userLogin(loginData:LoginData){
          let result:UserLoginResponseData = await reqUserLogin(loginData);
          if(result.code==200){
                this.userInfo = result.data;
                //本地存储持久化存储用户信息
              SET_TOKEN(JSON.stringify(this.userInfo))
                return 'ok';
          }else {
              return Promise.reject(new Error(result.message));

          }

        },
        //用户退出登录
         userLogout(){
         this.userInfo = {name:'',token:''};
         REMOVE_TOKEN();
        },
        //查询微信扫码的接口（看本地存储是否拥有用户信息）
        queryState(){
           let timer = setInterval(()=>{
              if( GET_TOKEN()){
                  this.visible=false;
                  this.userInfo=JSON.parse(GET_TOKEN() as string);
                  clearInterval(timer);
              }
           },1000)

        }
    },
    getters:{

    }
})

export default useUserStore;
